/*
  Wemos D1 Mini - Web-based PWM Controller for 4-Wire PC Fan
  ------------------------------------------------------------
  - Hosts a webpage with a slider (0-100%) to control fan speed
  - Outputs 1kHz PWM on D5 (GPIO14) -> fan Blue (PWM) wire
  - Reads RPM from fan Green (Tach) wire on D6 (GPIO12) via gated 500ms polling

  Wiring:
    Fan Black (GND)  -> Wemos GND (and 12V supply GND - common ground!)
    Fan Yellow (12V) -> 12V supply (NOT the Wemos 3V3/5V pin)
    Fan Blue (PWM)   -> Wemos D5 (GPIO14)
    Fan Green (Tach) -> Wemos D6 (GPIO12)  [optional]
*/

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// ---------- USER CONFIG ----------
const char* ssid     = "SSID";
const char* password = "PASSWORD";

const int PWM_PIN   = D5;   // GPIO14 -> fan PWM (blue) wire
const int TACH_PIN  = D6;   // GPIO12 -> fan tach (green) wire
const bool USE_TACH = true; // set false if you didn't wire the tach pin

const unsigned long RPM_INTERVAL_MS = 3000; // check RPM every 3 seconds
const unsigned long RPM_WINDOW_MS   = 500;  // sample tach pulses for 500ms
// ----------------------------------

ESP8266WebServer server(80);

volatile unsigned long tachPulses = 0;
unsigned long lastRpmCycle = 0;
bool samplingTach = false;
int currentRPM = 0;
int currentPercent = 50; // startup duty cycle

void ICACHE_RAM_ATTR tachISR() {
  tachPulses++;
}

const char htmlPage[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Fan Control</title>
  <style>
    body { font-family: Arial, sans-serif; background:#1e1e1e; color:#eee;
           text-align:center; padding-top:40px; }
    h1 { font-size: 1.6em; }
    .slider { width: 80%; max-width: 400px; height: 30px; }
    .value { font-size: 2.5em; margin: 20px 0; }
    .rpm { font-size: 1.2em; color: #9fd; margin-top: 10px; }
    button { background:#333; color:#eee; border:1px solid #555; padding:10px 18px;
             margin:6px; border-radius:6px; font-size:1em; }
    button:active { background:#555; }
  </style>
</head>
<body>
  <h1>PC Fan Speed Control</h1>
  <div class="value" id="pct">--%</div>
  <input type="range" min="0" max="100" value="50" class="slider" id="slider">
  <div>
    <button onclick="setVal(0)">Off</button>
    <button onclick="setVal(50)">50%</button>
    <button onclick="setVal(100)">Full</button>
  </div>
  <div class="rpm" id="rpm">RPM: --</div>

<script>
  const slider = document.getElementById('slider');
  const pct = document.getElementById('pct');
  const rpmEl = document.getElementById('rpm');

  function sendValue(v) {
    fetch('/set?value=' + v);
  }

  function setVal(v) {
    slider.value = v;
    pct.innerText = v + '%';
    sendValue(v);
  }

  slider.oninput = function() {
    pct.innerText = this.value + '%';
  };
  slider.onchange = function() {
    sendValue(this.value);
  };

  function poll() {
    fetch('/status').then(r => r.json()).then(d => {
      pct.innerText = d.percent + '%';
      slider.value = d.percent;
      rpmEl.innerText = 'RPM: ' + d.rpm;
    });
  }
  setInterval(poll, 2000);
  poll();
</script>
</body>
</html>
)rawliteral";

void handleRoot() {
  server.send_P(200, "text/html", htmlPage);
}

void handleSet() {
  if (server.hasArg("value")) {
    int percent = server.arg("value").toInt();
    percent = constrain(percent, 0, 100);
    currentPercent = percent;
    int duty = map(percent, 0, 100, 0, 1023);
    analogWrite(PWM_PIN, duty);
  }
  server.send(200, "text/plain", "OK");
}

void handleStatus() {
  String json = "{\"percent\":" + String(currentPercent) +
                ",\"rpm\":" + String(currentRPM) + "}";
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);

  pinMode(PWM_PIN, OUTPUT);
  analogWriteRange(1023); // keep 10-bit (0-1023) duty cycle scale
  analogWrite(PWM_PIN, map(currentPercent, 0, 100, 0, 1023));

  if (USE_TACH) {
    pinMode(TACH_PIN, INPUT_PULLUP);
  }

  WiFi.mode(WIFI_STA);
  WiFi.setSleepMode(WIFI_NONE_SLEEP); // keep Wi-Fi responsive for incoming HTTP requests
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected! IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.on("/set", handleSet);
  server.on("/status", handleStatus);
  server.begin();
  Serial.println("HTTP server started");

  lastRpmCycle = millis();
}

void loop() {
  server.handleClient();

  if (USE_TACH) {
    unsigned long now = millis();

    // Start a 500ms sampling window every 3 seconds
    if (!samplingTach && (now - lastRpmCycle >= RPM_INTERVAL_MS)) {
      tachPulses = 0;
      samplingTach = true;
      lastRpmCycle = now;
      attachInterrupt(digitalPinToInterrupt(TACH_PIN), tachISR, FALLING);
    }
    // End sampling window and calculate RPM
    else if (samplingTach && (now - lastRpmCycle >= RPM_WINDOW_MS)) {
      detachInterrupt(digitalPinToInterrupt(TACH_PIN));
      samplingTach = false;

      // Scale pulses from 500ms window to 60 seconds, divided by 2 pulses/rev
      currentRPM = (tachPulses * 60000UL) / (RPM_WINDOW_MS * 2);
    }
  }
}
